package com.ruoyi.redis;

import com.ruoyi.redis.util.PropertiesUtil;
import com.ruoyi.redis.util.RedisShardedPoolUtil;

public class RedisDistributedLock {
    static String CLOSE_ORDER_TASK_LOCK = "CLOSE_ORDER_TASK_LOCK";

    public void redisDemo1() {
        System.out.println("关闭订单定时任务启动");
        long lockTimeout = 5000L;
        //这个方法的缺陷在这里，如果setnx成功后，锁已经存到Redis里面了，服务器异常关闭重启，将不会执行closeOrder，
        //也就不会设置锁的有效期，这样的话锁就不会释放了，就会产生死锁
        Long setnxResult = RedisShardedPoolUtil.setnx(CLOSE_ORDER_TASK_LOCK,
                String.valueOf(System.currentTimeMillis() + lockTimeout));
        if (setnxResult != null && setnxResult.intValue() == 1) {
            //如果返回值为1，代表设置成功，获取锁
            closeOrder(CLOSE_ORDER_TASK_LOCK);
        } else {
            System.out.println("没有获得分布式锁:{" + CLOSE_ORDER_TASK_LOCK + "}");
        }
        System.out.println("关闭订单定时任务结束");
    }

    private void closeOrder(String lockName) {
        //对锁设置有效期
        RedisShardedPoolUtil.expire(lockName, 5);//有效期为5秒，防止死锁
        System.out.println("获取锁:{" + CLOSE_ORDER_TASK_LOCK + "},ThreadName:{" + Thread.currentThread().getName() + "}");
        //执行业务
        int hour = Integer.parseInt(PropertiesUtil.getProperty("close.order.task.time.hour", "2"));
        //执行完业务后，释放锁
        RedisShardedPoolUtil.del(CLOSE_ORDER_TASK_LOCK);
        System.out.println("释放锁:{" + CLOSE_ORDER_TASK_LOCK + "},ThreadName:{" + Thread.currentThread().getName() + "}");
        System.out.println("=================================");
    }

}
